In [1]:
greek = ["Alpha", "Beta", "Gamma", "Delta"]
In [2]:
for element in greek:
print(element)
Sometimes you need the index of an element and the element itself while you iterate through a list. This can be achived with the enumerate function.
In [3]:
for i, e in enumerate(greek):
print(e + " is at index: " + str(i))
The above is taking advantage of tuple decomposition, because enumerate generates a list of tuples. Let's look at this more explicitly.
In [4]:
list_of_tuples = [(1,2,3),(4,5,6), (7,8,9)]
for (a, b, c) in list_of_tuples:
print(a + b + c)
If you have two or more lists you want to iterate over together you can use the zip function.
In [5]:
for e1, e2 in zip(greek, greek):
print("Double Greek: " + e1 + e2)
You can also iterate over tuples
In [6]:
for i in (1,2,3):
print(i)
and dictionaries in various ways
In [7]:
elements = {
"H": "Hydrogen",
"He": "Helium",
"Li": "Lithium",
}
In [8]:
for key in elements: # Over the keys
print(key)
In [9]:
for key, val in elements.items(): # Over the keys and values
print(key + ": " + val)
In [10]:
for val in elements.values():
print(val)
In [11]:
x = 5
if x % 2 == 0: # Checks if x is even
print(str(x) + " is even!!!")
if x % 2 == 1: # Checks if x is odd
print(str(x) + " is odd!!!")
In the above example the second condition is somewhat redundant because if x is not even it is odd. There's a better way of expressing this.
In [12]:
if x % 2 == 0: # Checks if x is even
print(str(x) + " is even!!!")
else: # x is odd
print(str(x) + " is odd!!!")
You can have more than two conditions.
In [13]:
if x % 4 == 0:
print("x divisible by 4")
elif x % 3 == 0 and x % 5:
print("x divisible by 3 and 5")
elif x % 1 == 0:
print("x divisible by 1")
else:
print("I give up")
Note how only the first conditional branch that matches gets executed. The else conditions is a catch all condition that would have executed if none of the other branches had been chosen.
You can use the for keyword to generate new lists with data using list comprehensions.
In [14]:
r1 = []
for i in range(10):
r1.append(i**2)
# Equivalent to the loop above.
r2 = [i**2 for i in range(10)]
print(r1)
print(r2)
In [15]:
r1 = []
for i in range(30):
if (i%2 == 0 and i%3 == 0):
r1.append(i)
# Equivalent to the loop above.
r2 = [i for i in range(30) if i%2==0 and i%3==0]
print(r1)
print(r2)